{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Let's run our Age and Gender Detector\n",
    "\n",
    "- Please see https://github.com/yu4u/age-gender-estimation for source code project.\n",
    "- In this notebook we re-use the model trained by yu4u"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import cv2\n",
    "import dlib\n",
    "import sys\n",
    "import numpy as np\n",
    "import argparse\n",
    "from contextlib import contextmanager\n",
    "from wide_resnet import WideResNet\n",
    "from keras.utils.data_utils import get_file\n",
    "\n",
    "# Load our cassade classifier for faces\n",
    "face_classifier = cv2.CascadeClassifier('./Haarcascades/haarcascade_frontalface_default.xml')\n",
    "\n",
    "# Load our pretrained model for Gender and Age Detection\n",
    "pretrained_model = \"https://github.com/yu4u/age-gender-estimation/releases/download/v0.5/weights.28-3.73.hdf5\"\n",
    "modhash = 'fbe63257a054c1c5466cfd7bf14646d6'\n",
    "\n",
    "# Face Detection function\n",
    "def face_detector(img):\n",
    "    # Convert image to grayscale for faster detection\n",
    "    gray = cv2.cvtColor(img.copy(),cv2.COLOR_BGR2GRAY)\n",
    "    faces = face_classifier.detectMultiScale(gray, 1.3, 5)\n",
    "    if faces is ():\n",
    "        return False ,(0,0,0,0), np.zeros((1,48,48,3), np.uint8), img\n",
    "    \n",
    "    allfaces = []   \n",
    "    rects = []\n",
    "    for (x,y,w,h) in faces:\n",
    "        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n",
    "        roi = img[y:y+h, x:x+w]\n",
    "        roi_groiray = cv2.resize(roi, (64, 64), interpolation = cv2.INTER_AREA)\n",
    "        allfaces.append(roi)\n",
    "        rects.append((x,w,y,h))\n",
    "    return True, rects, allfaces, img\n",
    "\n",
    "# Define our model parameters\n",
    "depth = 16\n",
    "k = 8\n",
    "weight_file = None\n",
    "margin = 0.4\n",
    "image_dir = None\n",
    "\n",
    "# Get our weight file \n",
    "if not weight_file:\n",
    "    weight_file = get_file(\"weights.28-3.73.hdf5\", pretrained_model, cache_subdir=\"pretrained_models\",\n",
    "                           file_hash=modhash, cache_dir=Path(sys.argv[0]).resolve().parent)\n",
    "\n",
    "# load model and weights\n",
    "img_size = 64\n",
    "model = WideResNet(img_size, depth=depth, k=k)()\n",
    "model.load_weights(weight_file)\n",
    "\n",
    "# Initialize Webcam\n",
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "while True:\n",
    "    ret, frame = cap.read()\n",
    "    ret, rects, faces, image = face_detector(frame)\n",
    "    preprocessed_faces = []\n",
    "    i = 0\n",
    "    if ret:\n",
    "        for (i,face) in enumerate(faces):\n",
    "            face = cv2.resize(face, (64, 64), interpolation = cv2.INTER_AREA)\n",
    "            preprocessed_faces.append(face)\n",
    "\n",
    "        # make a prediction on the faces detected\n",
    "        results = model.predict(np.array(preprocessed_faces))\n",
    "        predicted_genders = results[0]\n",
    "        ages = np.arange(0, 101).reshape(101, 1)\n",
    "        predicted_ages = results[1].dot(ages).flatten()\n",
    "\n",
    "        # draw results\n",
    "        for (i, f) in enumerate(faces):\n",
    "            label = \"{}, {}\".format(int(predicted_ages[i]),\n",
    "                                        \"F\" if predicted_genders[i][0] > 0.5 else \"M\")\n",
    "\n",
    "        #Overlay our detected emotion on our pic\n",
    "        label_position = (rects[i][0] + int((rects[i][1]/2)), abs(rects[i][2] - 10))\n",
    "        i =+ 1\n",
    "        cv2.putText(image, label, label_position , cv2.FONT_HERSHEY_SIMPLEX,1, (0,255,0), 2)\n",
    "\n",
    "    cv2.imshow(\"Emotion Detector\", image)\n",
    "    if cv2.waitKey(1) == 13: #13 is the Enter Key\n",
    "        break\n",
    "\n",
    "cap.release()\n",
    "cv2.destroyAllWindows()      "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Note if you get the following error, you need to enable your webcam \n",
    "<img src=\"error.jpg\">\n",
    "### Enable your webcam by doing the following:\n",
    "<img src=\"webcam.jpg\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run these lines if your webcam fails to be realesed due to error in code\n",
    "cap.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
